// pages/project-detail/project-detail.js
import {
  activeDetail,
  setProPay,
  projPayUpdateOrder,
  itemShoppingCart
} from '../../api/apis.js'
let WxParse = require('../../plugin/wxParse/wxParse.js');
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    bannerConfig: {
      indicatorDots: true, //小点
      autoplay: true, //是否自动轮播
      interval: 5000, //间隔时间
      duration: 800 //滑动时间
    },
    detail: {},
    phone: '',
    name: '',
    count: 1,
    reduceBtn: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      mid: options.did,
      vipInfo: app.globalData.vipInfo
    })
    this._initData()
  },
  _initData() {
    activeDetail({
      data: {
        id: this.data.mid
      },
      success: res => {
        if (res.state) {
          let detail = res.data.content || "" //=== null ? '' : res.data.content.replace(/<img/g, "<img style='max-width:100%'")
          if (this.data.vipInfo.isVIP) {
            this.setData({
              projectVipPrice: res.data.sku[0].firstPay * (1 - this.data.vipInfo.BaseDiscount) * (1 - this.data.vipInfo.qdis.FurtureDiscount),
            })
          }
          WxParse.wxParse('article', 'html', detail, this, 5)
          // detail = detail.replace(/<section/g, "<div")
          // detail = detail.replace(/<\/section/g, "</div")
          // res.data.content = detail
          res.data.sku[0].selected = true
          this.setData({
            detail: res.data,
            sizeChecked: res.data.sku[0]
          })
          this.calculate()
        }
      }
    })
  },
  openMap() {
    if (this.data.detail.lat || this.data.detail.lng) {
      wx.openLocation({
        latitude: this.data.detail.lat,
        longitude: this.data.detail.lng,
        address: this.data.detail.adress
      })
    }
  },
  getBuy(e) {
    this.setData({
      showModalStatus: true,
      modalBtnText: e.currentTarget.dataset.text,
      buyORadd: e.currentTarget.dataset.next
    })
  },
  hideModal() {
    this.setData({
      boxShow: false
    })
  },
  setName(e) {
    this.setData({
      name: e.detail.value
    })
  },
  setPhone(e) {
    this.setData({
      phone: e.detail.value
    })
  },
  finalBuy() {
    if (!this.data.name.trim() || !this.data.phone.trim()) {
      wx.showToast({
        title: '请将姓名和手机号填写完整',
        icon: 'none',
        duration: 1000
      })
      return false
    }
    if (this.data.phone.trim().length !== 11) {
      wx.showToast({
        title: '请填写正确的手机号',
        icon: 'none',
        duration: 1000
      })
      return false
    }
    wx.showLoading({
      title: '提交中...',
      mask: true
    })
    setProPay({
      data: {
        openid: app.globalData.openid,
        name: this.data.name,
        phone: this.data.phone,
        id: this.data.mid,
        remark: ''
      },
      success: res => {
        wx.hideLoading()
        if (res.state) {
          let params = JSON.parse(res.data.parameters)
          if (parseFloat(this.data.detail.price) > 0) {
            wx.requestPayment({
              nonceStr: params.nonceStr,
              package: params.package,
              paySign: params.paySign,
              signType: params.signType,
              timeStamp: params.timeStamp,
              success: response => {
                wx.showToast({
                  title: '支付成功',
                  mask: true,
                  duration: 2000,
                  success: (e) => {
                    setTimeout(() => {
                      wx.navigateTo({
                        url: '../order-list/order-list',
                      })
                    }, 2000)
                  }
                })
              },
              complete: response => {
                if (response.errMsg == "requestPayment:cancel" || response.errMsg == "requestPayment:fail cancel") {
                  this._updateOrder(res, 'fail')
                }
              }
            })
          } else {
            this._updateOrder(res, 'ok')
          }
        }
      }
    })
  },
  _updateOrder(res, state) {
    projPayUpdateOrder({
      data: {
        orderid: res.data.out_trade_no,
        payStatus: state,
        payReamrk: '',
        openid: app.globalData.openid
      },
      success: res => {
        if (res.state) {
          wx.showToast({
            title: state == 'ok' ? '支付成功' : '支付失败',
            icon: 'none',
            mask: true,
            duration: 2000,
            success: (e) => {
              setTimeout(() => {
                wx.navigateTo({
                  url: '../order-list/order-list',
                })
              }, 2000)
            }
          })
        }
      }
    })
  },

  //从商品详情处复制过来
  clickCapacity: function(e) {
    let index = e.currentTarget.dataset.index
    let current = "detail.sku[" + index + "].selected"
    this.data.detail.sku.map((item, index) => {
      item.selected = false
      return item
    })
    this.setData({
      detail: this.data.detail,
      [current]: true,
      sizeChecked: this.data.detail.sku[index]
    })
    this.calculate()
  },
  cancelModal: function() {
    this.setData({
      showModalStatus: false
    })
  },
  addCount: function() {
    let count = this.data.count
    this.setData({
      count: ++count
    })
    this.calculate()
    this.setData({
      reduceBtn: true
    })
  },
  reduceCount: function() {
    let count = this.data.count
    if (count > 1) {
      count--
      this.setData({
        count: count
      })
      this.calculate()
      if (count <= 1) {
        this.setData({
          reduceBtn: false
        })
      }
    }
  },
  //计算价格函数
  calculate() {
    let skus = this.data.detail.sku
    let checkedSku = {}
    for (let i = 0; i <= skus.length - 1; i++) {
      if (skus[i].selected) {
        checkedSku = skus[i]
        break
      }
    }
    this.setData({
      total: checkedSku.firstPay * this.data.count
    })
  },
  addCart() {
    if (this.data.buyORadd == 1) {
      wx.showLoading({
        title: '加入中...',
        mask: true
      })
      itemShoppingCart({
        data: {
          openid: app.globalData.openid,
          product_Id: this.data.mid,
          sku_id: this.data.sizeChecked.id,
          variable: this.data.count
        },
        success: res => {
          wx.hideLoading()
          if (res.state) {
            wx.showToast({
              title: '添加成功'
            })
            this.setData({
              showModalStatus: false
            })
          }
        }
      })
    } else if (this.data.buyORadd == 2) {
      let confirmProduct = [{
        img: this.data.sizeChecked.img.URL,
        title: this.data.detail.title,
        cpacity: this.data.sizeChecked.title,
        price: this.data.sizeChecked.firstPay,
        count: this.data.count,
        product_Id: this.data.mid,
        sku_id: this.data.sizeChecked.id
      }]
      wx.setStorage({
        key: 'confirmProduct',
        data: confirmProduct,
        success: res => {
          wx.navigateTo({
            url: '../project-confirm/project-confirm',
          })
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})